#!/bin/bash
#
# author: test
# email: test
# date: 2022/2/19 09:50
# version: v1.0.0
#
# 功能描述:
# 构建发布前端项目

# 编译项目
function compile_project() {
  local b
  if [ "$branch" == 'test' ]; then
    b="stage"
    docker run --rm -v "${workspace}":/app -w /app node:16-alpine3.12 \
      sh -c "rm -rf ${workspace}/dist && npm install --registry=https://registry.npm.taobao.org && npm run build:$b"
  else
    b="prod"
    # 生产环境 jenkins 部署在 k8s 中，但是 docker 又是用的宿主机上的二进制文件
    docker run --rm -v /data/jenkins/jenkins_data/workspace/gupao-p7store-ui:/app -w /app node:16-alpine3.12 \
      sh -c "rm -rf ${workspace}/dist && npm install --registry=https://registry.npm.taobao.org && npm run build:$b"
  fi
}

# 构建镜像
function build_image() {
  local tag
  tag="$(git rev-list -n 1 HEAD | cut -c-10)$(date +%Y%m%d%H%M%S)"
  local image_name="${registry}/${namespace}/${project_name}:${tag}"
  echo "${tag}" > "${workspace}/deploy/tag.txt"
  echo "start building docker image ${image_name}"

  docker build --no-cache -t "${image_name}" -f "${workspace}/deploy/Dockerfile" "${workspace}" || exit
  docker push "${image_name}"

  local latest_image="${registry}/${namespace}/${project_name}:latest"
  docker tag "${image_name}" "${latest_image}"
  docker push "${latest_image}"

  docker rmi "${image_name}"
  docker rmi "${latest_image}"
}

# main
function main() {
  local options
  while getopts 'R:W:N:P:B:' options; do
    case "$options" in
      R) registry="$OPTARG" ;;
      W) workspace="$OPTARG" ;;
      N) namespace="$OPTARG" ;;
      P) project_name="$OPTARG" ;;
      B) branch="$OPTARG" ;;
      *) echo "param error ..." && exit 1 ;;
    esac
  done

  if [ -z "$registry" ] || [ -z "$workspace" ] || [ -z "$namespace" ] || [ -z "$project_name" ] || [ -z "$branch" ]; then
    echo "miss param ..."
    exit 1
  fi

  compile_project
  build_image
}

main "$@"
